package com.zhongyouyun.other.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.cqyc.model.WxUserModel;
import com.zhongyouyun.jyj.model.SspWxUserModel;
import com.zhongyouyun.other.model.TokenUtil;
import com.zhongyouyun.utils.SpringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class CORSAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class);

    public CORSAuthenticationFilter() {
        super();
    }

    @Override
    public boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String type = request.getHeader("type");
        if (ObjectUtil.isNotEmpty(type)) {
            if ("jyj_mobile".equals(type)) {
                String newtoken = request.getHeader(TokenUtil.tokenHeard);
                if (!ObjectUtil.isNotEmpty(newtoken)) {
                    return false;
                } else {
                    RedisConfig redisConfig = SpringUtil.getBean(RedisConfig.class);
                    SspWxUserModel userModel = (SspWxUserModel) redisConfig.get(newtoken);
                    if (!ObjectUtil.isNotEmpty(userModel)) {
                        return false;
                    }

                }
            }
            if ("cqyc_mobile".equals(type)) {
                String newtoken = request.getHeader(TokenUtil.tokenHeard);
                if (!ObjectUtil.isNotEmpty(newtoken)) {
                    return false;
                } else {
                    RedisConfig redisConfig = SpringUtil.getBean(RedisConfig.class);
                    WxUserModel userModel = (WxUserModel) redisConfig.get(newtoken);
                    if (!ObjectUtil.isNotEmpty(userModel)) {
                        return false;
                    }

                }
            }
            return true;
        } else {
            Subject subject = SecurityUtils.getSubject();
            String sessionId = null;
            if (ObjectUtil.isNotNull(subject.getSession().getId())) {
                sessionId = subject.getSession().getId().toString();
            }
            RedisConfig redisConfig = SpringUtil.getBean(RedisConfig.class);
            String newtoken = request.getHeader(TokenUtil.tokenHeard);
            if (null == newtoken || "".equals(newtoken)) {
//            System.out.println("-------------------token为空");
                return false;
            }
            //验证token的真实性
            try {
//            System.out.println(newtoken);
                TokenUtil.getTokenBody(newtoken);
                if (ObjectUtil.isNotNull(sessionId)) {
                    if (ObjectUtil.isNotNull(redisConfig.get(sessionId))) {
                        String token = redisConfig.get(sessionId).toString();
                        if (!token.equals(newtoken)) {
                            return false;
                        }
                    } else {
                        System.out.println(request.getHeader("Token"));
                        if (ObjectUtil.isNotEmpty(request.getHeader("Token"))) {
                            String token = redisConfig.get(request.getHeader("Token")).toString();
                            if (!token.equals(newtoken)) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
                }
                Object u = SecurityUtils.getSubject().getPrincipal();
                if (u instanceof UserModel) {
                    UserModel userModel = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
                    if (ObjectUtil.isNull(userModel)) {
                        return false;
                    }
                } else if (u instanceof UserModel) {
                    //这里可能处理手机端
                    UserModel userModel = (UserModel) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
                    if (ObjectUtil.isNull(userModel)) {
                        return false;
                    }
                }
                //这里可能验证token的效

            } catch (Exception e) {
                //e.printStackTrace();
                System.out.println("----------------token有问题");
                return false;
            }
            return true;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("status", 2);
        map.put("msg", "未登录");
        writer.write(JSON.toJSONString(map));
        writer.close();
        return false;
    }
}